<template>
  <div class="join-addEdit">
    <el-dialog :append-to-body="true" :title="title" v-model="show" @close="cancelFun" :close-on-click-modal="false"
      destroy-on-close>
      <el-form :model="form" ref="formRef" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="封面图:" prop="images" style="height: auto">
          <el-upload :http-request="upload" action="" list-type="picture-card" :on-preview="imgPreview"
            :on-remove="imgRemove" :file-list="form.images" accept=".jpg,.jpeg,.png,.gif,.JPG,.JPEG,.GIF" :limit="1"
            :on-exceed="limitFun">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="isbn编码:" prop="isbn">
          <div class="isbn-box" style="width: 100%;display:flex;">
            <el-input type="text" placeholder="请输入内容" size="large" v-model="form.isbn" maxlength="50" show-word-limit>
              <!-- <template #append>
              <el-button :icon="Search" @click="getIsbnFun">
                <el-icon class="search-icon">
                  <Search />
                </el-icon>
              </el-button>
            </template> -->
            </el-input>
            <el-button style="height: 40px;" type="primary" :icon="Search" @click="getIsbnFun()">
              <el-icon class="search-icon">
                <Search />
              </el-icon>
            </el-button>
          </div>

        </el-form-item>
        <el-form-item label="书籍类型:" prop="type">
          <el-select v-model="form.type" class="m-2" placeholder="书籍类型" size="large" @change="changeType">
            <el-option v-for="item in types" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="书籍名称:" prop="name">
          <el-input type="text" placeholder="请输入内容" size="large" v-model="form.name" maxlength="50" show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item label="重量:" prop="zhongliang">
          <el-input type="text" placeholder="请输入内容" size="large" v-model="form.zhongliang" maxlength="50"
            show-word-limit> </el-input>
        </el-form-item>
        <el-form-item label="单价:" prop="dingjia">
          <el-input type="text" placeholder="请输入内容" size="large" v-model="form.dingjia" maxlength="50" show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item label="出版时间:" prop="chubantime">
          <el-date-picker v-model="form.chubantime" type="date" placeholder="出版时间" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="售价:" prop="price">
          <el-input type="text" placeholder="请输入内容" size="large" v-model="form.price" maxlength="50" show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item label="采购价:" prop="caigouprice">
          <el-input type="text" placeholder="请输入内容" size="large" v-model="form.caigouprice" maxlength="50"
            show-word-limit> </el-input>
        </el-form-item>
        <el-form-item label="维护人:" prop="weihuren">
          <el-select v-model="form.weihuren" class="m-2" placeholder="维护人" size="large" @change="changeWeihuren">
            <el-option v-for="item in persons" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="采购数量:" prop="caigoucount">
          <el-input type="text" placeholder="请输入内容" size="large" v-model="form.caigoucount" maxlength="50"
            show-word-limit> </el-input>
        </el-form-item>
        <el-form-item label="作者:" prop="zuozhename">
          <el-input type="text" placeholder="请输入内容" size="large" v-model="form.zuozhename" maxlength="50"
            show-word-limit> </el-input>
        </el-form-item>
        <el-form-item label="作者介绍:" prop="zuozhejieshao">
          <el-input v-model="form.zuozhejieshao" :rows="3" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="出版社:" prop="chubanshe">
          <el-input type="text" placeholder="请输入内容" size="large" v-model="form.chubanshe" maxlength="50"
            show-word-limit> </el-input>
        </el-form-item>
        <el-form-item label="书籍介绍:" prop="shujijieshao">
          <el-input v-model="form.shujijieshao" :rows="3" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="豆瓣评分:" prop="doubanScore">
          <el-input type="text" placeholder="请输入内容" size="large" v-model="form.doubanScore" maxlength="50"
            show-word-limit> </el-input>
        </el-form-item>
        <el-form-item label="豆瓣评分人数:" prop="doubannumScore">
          <el-input type="text" placeholder="请输入内容" size="large" v-model="form.doubannumScore" maxlength="50"
            show-word-limit> </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelFun" size="large">取消</el-button>
          <el-button type="primary" @click="confirmFun" size="large">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 图片预览 -->
    <el-dialog :append-to-body="true" v-model="showImages">
      <img style="width: 100%" :src="imageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script setup>
import { computed, onMounted, onUnmounted, ref, watch, defineEmits, reactive } from 'vue'
import { addServerUser, editServerUser } from '@api/person'
import { addShangpin, editShangpin } from '@api/book'
import { encode } from 'js-base64'
import md5 from 'js-md5'
import { ElMessage } from 'element-plus'
import * as qiniu from 'qiniu-js'
import { useQiniuStore } from '@/pinia/qiniu'
import { getShujiType } from '@api/bookType'
import { getServerUserList } from '@api/person'
import { getToken, getIsbn } from '@api/common'

const qiniuStore = useQiniuStore()

const props = defineProps({
  status: {
    type: String,
    default: null
  },
  show: {
    type: Boolean,
    default: null
  },
  addEditData: {
    type: Object,
    default: {
      id: '',
      name: ''
    }
  }
})

const formRef = ref()

const form = ref({
  id: '',
  name: '',
  images: [],
  isbn: '',
  type: '',
  typename: '',
  zhongliang: '',
  dingjia: '',
  chubantime: '',
  price: '',
  caigouprice: '',
  weihuren: '',
  weihurenname: '',
  caigoucount: '',
  zuozhename: '',
  zuozhejieshao: '',
  chubanshe: '',
  shujijieshao: '',
  doubanScore: '',
  doubannumScore: ''
})

const rules = reactive({
  name: [{ required: true, message: '书籍名称不能为空!', trigger: 'blur' }],
  type: [{ required: true, message: '书籍类型不能为空!', trigger: 'blur' }],
  isbn: [{ required: true, message: 'isbn编码不能为空!', trigger: 'blur' }],
  // chubantime: [{ required: true, message: '出版时间不能为空!', trigger: 'blur' }],
  weihuren: [{ required: true, message: '维护人不能为空!', trigger: 'blur' }],
  // zuozhename: [{ required: true, message: '作者不能为空!', trigger: 'blur' }],
  // chubanshe: [{ required: true, message: '出版社不能为空!', trigger: 'blur' }],
  zhongliang: [
    {
      validator: (rule, value, callback) => {
        value = form.value.zhongliang
        if (!value) {
          // callback(new Error('重量不能为空!'))
          callback()
        } else if (!/^[+]?(0|([1-9]\d*))(\.\d+)?$/g.test(value)) {
          callback(new Error('请输入数字!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  dingjia: [
    {
      validator: (rule, value, callback) => {
        value = form.value.dingjia
        if (!value) {
          // callback(new Error('单价不能为空!'))
          callback()
        } else if (!/^[+]?(0|([1-9]\d*))(\.\d+)?$/g.test(value)) {
          callback(new Error('请输入数字!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  price: [
    {
      validator: (rule, value, callback) => {
        value = form.value.price
        if (!value) {
          // callback(new Error('售价不能为空!'))
          callback()
        } else if (!/^[+]?(0|([1-9]\d*))(\.\d+)?$/g.test(value)) {
          callback(new Error('请输入数字!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  caigouprice: [
    {
      required: true,
      validator: (rule, value, callback) => {
        value = form.value.caigouprice
        if (!value) {
          callback(new Error('采购价不能为空!'))
        } else if (!/^[+]?(0|([1-9]\d*))(\.\d+)?$/g.test(value)) {
          callback(new Error('请输入数字!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  caigoucount: [
    {
      required: true,
      validator: (rule, value, callback) => {
        value = form.value.caigouprice
        if (!value) {
          callback(new Error('采购数量不能为空!'))
        } else if (!/^[+]?(0|([1-9]\d*))(\.\d+)?$/g.test(value)) {
          callback(new Error('请输入数字!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  doubanScore: [
    {
      validator: (rule, value, callback) => {
        value = form.value.doubanScore
        if (!value) {
          callback()
        } else if (!/^[+]?(0|([1-9]\d*))(\.\d+)?$/g.test(value)) {
          callback(new Error('请输入数字!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  doubannumScore: [
    {
      validator: (rule, value, callback) => {
        value = form.value.doubannumScore
        if (!value) {
          callback()
        } else if (!/^[+]?(0|([1-9]\d*))(\.\d+)?$/g.test(value)) {
          callback(new Error('请输入数字!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

const emit = defineEmits(['hide-addEdit'])

const title = computed(() => {
  return props.status == 'add' ? '添加书籍' : '编辑书籍'
})

// 添加或编辑
function confirmFun() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      let res = ''
      let {
        id,
        name,
        images,
        isbn,
        type,
        typename,
        zhongliang,
        dingjia,
        chubantime,
        price,
        caigouprice,
        weihuren,
        weihurenname,
        caigoucount,
        zuozhename,
        zuozhejieshao,
        chubanshe,
        shujijieshao,
        doubanScore,
        doubannumScore
      } = form.value
      console.log(images)
      images = images.map((v) => v.url).join(',')

      let data = {
        name,
        images,
        isbn,
        type,
        typename,
        zhongliang,
        dingjia,
        chubantime,
        price,
        caigouprice,
        weihuren,
        weihurenname,
        caigoucount,
        zuozhename,
        zuozhejieshao,
        chubanshe,
        shujijieshao,
        doubanScore,
        doubannumScore
      }
      if (props.status == 'add') {
        res = await addShangpin(data)
      } else if (props.status == 'edit') {
        data.id = id
        res = await editShangpin(data)
      }

      if (res.code == 200) {
        ElMessage({
          message: '操作成功!',
          type: 'success'
        })
        emit('hide-addEdit', props.status)
      }
    }
  })
}

function cancelFun() {
  emit('hide-addEdit', 'cancel')
}

//获取列表
let token = ''
async function getQiNiuToken() {
  let res = await getToken()
  token = res.data.token
}

//上传多个
const uploadMultiple = async (file, name) => {
  /* 
  bucket: 上传的目标空间
	
  file: File 对象，上传的文件
	
  key: 文件资源名
	
  token: 上传验证信息，前端通过接口请求后端获得
	
  config: object，其中的每一项都为可选
*/

  // qiniu.upload(file: File, key: string, token: string, putExtra?: object, config?: object): observable
  const key = new Date().getTime()
  const observable = qiniu.upload(file, key, token)
  const subscription = observable.subscribe({
    next: (result) => {
      // 接收上传进度信息，result是带有total字段的 Object
      // loaded: 已上传大小; size: 上传总信息; percent: 当前上传进度
      console.log(result) // 形如：{total: {loaded: 1671168, size: 2249260, percent: 74.29856930723882}}
      // this.percent = result.total.percent.toFixed(0);
    },
    error: (errResult) => {
      // 上传错误后失败报错
      console.log(errResult)
      // this.message.error('上传失败');
    },
    complete: (result) => {
      // 接收成功后返回的信息

      if (result.key) {
        form.value.images = [
          {
            name: qiniuStore.qiniu + result.key,
            url: qiniuStore.qiniu + result.key
          }
        ]

        ElMessage({
          message: '上传成功!',
          type: 'success'
        })
      }
    }
  })
}

//上传
const loading = ref()
const upload = async (params) => {
  let that = this
  //限制图片大小
  let size = params.file.size / 1024 / 1024 < 4

  if (!size) {
    this.$message.error('上传图片的大小不能超过 4M!')
    return false
  }

  // loading.value = ElLoading.service({
  //   lock: true,
  //   text: '加载中'
  // })

  // let thisRef = 'imgComRef';
  // let uploadFile = "";
  // uploadFile = this.$refs[thisRef].uploadFiles;

  // this.$refs[thisRef].clearFiles();

  //上传控件的最后一个文件信息
  // let len = uploadFile.length;
  // let file = uploadFile[len - 1].raw;
  // let uid = uploadFile[len - 1].uid;
  // let name = uploadFile[len - 1].name;
  await uploadMultiple(params.file)
}

//超出限制
function limitFun() {
  ElMessage.error('最多上传1张!')
}
//图片删除
function imgRemove(file, filelist) {
  form.value.image = []
}
//图片预览
const imageUrl = ref('')
const showImages = ref(false)
function imgPreview(file) {
  imageUrl.value = file.url
  showImages.value = true
}

// 获取书籍类型
const types = ref([])
const getTypes = async () => {
  let res = await getShujiType()

  if (res.code == 200) {
    types.value = res.data.map((v) => {
      return {
        label: v.name,
        value: v.id + ''
      }
    })

    if (res.data && res.data.length) {
      form.value.type = types.value[0].value
      // form.value.weihurenname = types.value[0].label
    }
  }
}

// 员工列表
const persons = ref([])
const getPersons = async () => {
  let res = await getServerUserList()

  if (res.code == 200) {
    persons.value = res.data.map((v) => {
      return {
        label: v.username,
        value: v.id + ''
      }
    })

    if (res.data && res.data.length) {
      form.value.weihuren = persons.value[0].value
      form.value.weihurenname = persons.value[0].label
    }
  }
}

// 改变维护人
const changeWeihuren = (val) => {
  form.value.weihurenname = persons.value.filter((v) => v.value == val)[0].label
}

// 改变书籍类型
const changeType = (val) => {
  form.value.typename = types.value.filter((v) => v.value == val)[0].label
}

// 获取isbn查询
const getIsbnFun = async () => {
  let res = await getIsbn({ isbn: form.value.isbn })
  res = res.data.data
  const {
    name,
    author,
    authorIntro,
    photoUrl,
    publishing,
    // published	,
    description,
    doubanScore
  } = res

  if (name) {
    form.value.name = name
  }
  if (author) {
    form.value.zuozhename = author
  }
  if (authorIntro) {
    form.value.zuozhejieshao = authorIntro
  }
  if (photoUrl) {
    form.value.images = [
      {
        url: photoUrl,
        name: photoUrl
      }
    ]
  }
  if (publishing) {
    form.value.chubanshe = publishing
  }
  if (description) {
    form.value.shujijieshao = description
  }
  if (publishing) {
    form.value.chubanshe = publishing
  }
  if (doubanScore + '') {
    form.value.doubanScore = doubanScore
  }
}

onMounted(() => {
  // getIsbnFun()
})

watch(
  () => props.addEditData,
  (newValue, oldValue) => {
    const {
      id,
      name,
      images,
      isbn,
      type,
      zhongliang,
      dingjia,
      chubantime,
      price,
      caigouprice,
      weihuren,
      weihurenname,
      caigoucount,
      zuozhename,
      zuozhejieshaom,
      chubanshe,
      shujijieshao,
      doubanScore,
      doubannumScore
    } = newValue
    console.log(images)
    form.value = {
      id,
      name,
      images,
      isbn,
      type,
      zhongliang,
      dingjia,
      chubantime,
      price,
      caigouprice,
      weihuren,
      weihurenname,
      caigoucount,
      zuozhename,
      zuozhejieshaom,
      chubanshe,
      shujijieshao,
      doubanScore,
      doubannumScore
    }

    getQiNiuToken()
    getTypes()
    getPersons()
  },
  { deep: true }
)
</script>
<style lang="scss">
.isbn-box {
  .el-input__wrapper {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
  }

  .el-button {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
  }
}
</style>

